/**
 * 一个页面应用，即一个完整的CURD操作页面引用一次
 * 内部操作建议打开对话框完成
 */

var app = {
    api : '/api/',
    md5_salt : '48024573fc3c5a35651c255a5daa43e9'
};

/**
 * Create a cookie with the given key and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain used when the cookie was set.
 *
 * @param String
 *            key The key of the cookie.
 * @param String
 *            value The value of the cookie.
 * @param Object
 *            options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object. If a negative value is specified (e.g. a date in the past), the cookie will be deleted. If set to null or omitted, the cookie will be a session cookie and will not be retained when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 *
 * Get the value of a cookie with the given key.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String
 *            key The key of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
app.cookie = function(key, value, options) {
    if (arguments.length > 1 && (value === null || typeof value !== "object")) {
        options = $.extend({}, options);
        if (value === null) {
            options.expires = -1;
        }
        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }
        return (document.cookie = [ encodeURIComponent(key), '=', options.raw ? String(value) : encodeURIComponent(String(value)), options.expires ? '; expires=' + options.expires.toUTCString() : '', options.path ? '; path=' + options.path : '', options.domain ? '; domain=' + options.domain : '', options.secure ? '; secure' : '' ].join(''));
    }
    options = value || {};
    var result, decode = options.raw ? function(s) {
        return s;
    } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

/**
 * 本地数据存取接口
 * @param key 被存储数据的主键
 * @param val 被存储数据的值：如果没有传参数，为获取值；如果为null，则为删除数据
 * @return mixed
 */
app.store = function (key, val) {
    if(arguments.length === 0) return false;
    if(arguments.length === 1) return JSON.parse(window.localStorage.getItem(key));
    if(val == null) return window.localStorage.removeItem(key);
    return window.localStorage.setItem(key, JSON.stringify(val));
}

/**
 * 跳转
 * @param url
 */
app.jump = function (url) {
    window.location = url;
}

/**
 * 错误提示
 * @param msg
 */
app.error = function (msg) {
    layer.msg(msg);
}

/**
 * 错误提示
 * @param msg
 * @param url
 */
app.success = function (msg, url) {
    layer.msg(msg);
    if(typeof url == 'undefined' || url == null || url == '') return;
    
    setTimeout(function(){
        window.location = url;
    },3000);
}

/**
 * GET请求
 * @param url
 * @param callback
 */
app.get = function (url, callback) {
    $.getJSON(app.api + url, function (res) {
        if(res.error == '0'){
        	app.success(res.message);
            callback(res);       
       }else {
           app.error(res.message); 
       }
    });
}

/**
 * post请求
 * @param url
 * @param callback
 */
app.post = function (url, data, callback) {
    $.post(app.api + url, data, function (res) {
    	if(res.error == '0'){
        	app.success(res.message);
            callback(res);       
       }else {
           app.error(res.message); 
       }
    },'json');
}

/**
 * 动态生成下拉框
 * @param ele
 * @param api
 * @param param
 * @param callback
 */
app.buildSelect = function (ele, api, param, callback) {
    var $ele = $(ele);
    var emptys = $ele.attr('empty');
    var str = "";
    if(typeof emptys != 'undefined' && emptys!='') str += '<option value="">' +emptys + '</option>';
    if(typeof param == 'undefined' || param == '') param = {};
    $ele.empty().append(str);
    $.getJSON(app.api + api, param, function(res){
        if(res.error == '0' && res.data != null && res.data.length >0){
            str += app.buildOptions(res.data,$ele.attr('value'));
        }
        $ele.empty().append(str);
        callback();
    });
}


/**
 * 动态生成下拉框
 * @param ele
 * @param api
 * @param param
 * @param callback
 */
app.buildSelectTree = function (ele, api, param, callback) {
    var $ele = $(ele);
    var emptys = $ele.attr('empty');
    var str = "";
    if(typeof emptys != 'undefined' && emptys!='') str += '<option value="">' +emptys + '</option>';
    if(typeof param == 'undefined' || param == '') param = {};
    $ele.empty().append(str);
    $.getJSON(app.api + api, param, function(res){
        if(res.error == '0' && res.data != null && res.data.length >0) {
            str += app.buildOptions(res.data, $ele.attr('value'), 0);
        }
        $ele.empty().append(str);
        callback();
    });
}

/**
 * 构建Select的选项
 * @param data 数据
 * @param type 类型,如果为tree，则为树形结构
 * @param value 默认选中值
 * @param level 层级，可选
 * @returns {string}
 */
app.buildOptions = function (data, value,level){
    var str = "";
    var isTree = true;
    if(typeof level == 'undefined') {
        level = 0;
        isTree = false
    }

    for(var i = 0; i < data.length ; i++ ){
        str += '<option value="'+data[i].id+'"';
        if(value == data[i].id+'') str += ' selected ';
        str += '>';
        str += (isTree ? buildSep(level) : '') + data[i].title + '</option>';
        if(isTree && data[i].children){
            str += app.buildOptions(data[i].children, value,level+1)
        }
    }
    return str;

    function buildSep(level) {
        var sp = '';
        for(var j=0;j<level;j++) sp += '--';
        if(sp != '') sp = '|' + sp;
        return sp;
    }
}

/**
 * 重新构建本地路径
 */
app.appendLocation = function (p,v){
    var q = '/' + p + '/';
    var p = window.location.href.indexOf(q);
    if(p > 0){
        var sq = window.location.href.substr(p+q.length);
        var sp = sq.indexOf('/');
        if(sp > 0){
            return window.location.href.substr(0,p + q.length) + v + sq.substr(sp);
        } else {
            return window.location.href.substr(0,p + q.length) + v;
        }
    }else{
        return window.location.href + q + v;
    }
}